package com.tdcy.framework.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.tdcy.framework.exception.BaseException;

/**
 * <p>
 * 字符串工具类
 * </p>
 * <p>
 * <b>最后修改时间：</b><br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2010-12-17下午02:37:17
 * </p>
 * 
 * @version 1.0
 */
public class StringUtils {

	private static Pattern SQL_IN_P = Pattern.compile(",");
	// 过滤掉查询条件中的"'"
	private static Pattern SQL_Filter_P = Pattern.compile("'");

	/**
	 * 
	 * Return type: String
	 * 
	 * @Title: sqlInQueryStr
	 * @Description: 将 a,b,c 变为 'a','b','c'
	 * @param s
	 * @return
	 */
	public static String sqlInQueryStr(String s) {
		return new StringBuilder().append('\'').append(SQL_IN_P.matcher(s).replaceAll("','")).append('\'').toString();
	}

	/**
	 * 
	 * Return type: String
	 * 
	 * @Title: sqlQueryStr
	 * @Description: 去掉查询条件中的"'"
	 * @param s
	 * @return
	 */
	public static String sqlQueryStr(String s) {
		return SQL_Filter_P.matcher(s).replaceAll("");
	}

	/**
	 * <p>
	 * 判断是否不为空串（或NULL）
	 * </p>
	 * <p>
	 * <b>最后修改时间：</b><br>
	 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2010-12-17下午03:51:08
	 * </p>
	 * 
	 * @param s
	 *            目标字符串
	 * @return True不是空串（或NULL），false是空串（或NULL）
	 */
	public static boolean isNotEmpty(String s) {
		return !isEmpty(s);
	}

	public static boolean equals(String s1, String s2) {
		if (s1 == null) {
			return s2 == null;
		}

		return s1.equals(s2);
	}

	public static String replace(String sourceStr, int beginIndex, int endIndex, String targetStr) {
		String resultStr = sourceStr.substring(0, beginIndex);
		resultStr += targetStr;
		resultStr += sourceStr.substring(endIndex);
		return resultStr;
	}

	public static String substring(String str, String beginStr, String endStr) {
		int beginIndex = str.indexOf(beginStr) + beginStr.length();
		int endIndex = str.indexOf(endStr);
		if (beginIndex < 0 || endIndex < 0 || endIndex < beginIndex) {
			return "";
		}
		return str.substring(beginIndex, endIndex);
	}

	public static String generateString(String expressionString, HashMap<String, String> variableMap) {
		StringBuilder resultData = new StringBuilder(1024);
		StringBuilder variableName = new StringBuilder(64);
		boolean isVariable = false;
		for (char dataChar : expressionString.toCharArray()) {
			if (dataChar == '}') {
				isVariable = false;
				String key = variableName.toString().toUpperCase();
				String value = variableMap.get(key);
				// resultData.append(value==null?"{"+key+"}=null":value);
				resultData.append(value == null ? "" : value);
			}
			if (isVariable) {
				variableName.append(dataChar);
			} else if (dataChar != '{' && dataChar != '}') {
				resultData.append(dataChar);
			}
			if (dataChar == '{') {
				isVariable = true;
				variableName = new StringBuilder(64);
			}
		}
		return resultData.toString();
	}

	public static byte[] decoderBASE64(String base64) throws IOException {
		byte[] b = null;
		b = new BASE64Decoder().decodeBuffer(base64);
		return b;
	}

	public static String encoderBASE64(byte[] s) {
		if (s == null)
			return null;
		return (new BASE64Encoder()).encode(s).replace("\r\n", "");
	}

	/*
	 * 16进制数字字符集
	 */
	private static String hexString = "0123456789ABCDEF";

	/*
	 * 将字符串编码成16进制数字,适用于所有字符（包括中文）
	 */
	public static String encoderHex(String str) {
		// 根据默认编码获取字节数组
		byte[] bytes = str.getBytes();
		StringBuilder sb = new StringBuilder(bytes.length * 2);
		// 将字节数组中每个字节拆解成2位16进制整数
		for (int i = 0; i < bytes.length; i++) {
			sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
			sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
		}
		return sb.toString();
	}

	/*
	 * 将16进制数字解码成字符串,适用于所有字符（包括中文）
	 */
	public static String decoderHex(String bytes) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length() / 2);
		// 将每2位16进制整数组装成一个字节
		for (int i = 0; i < bytes.length(); i += 2) {
			baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString.indexOf(bytes.charAt(i + 1))));
		}
		return new String(baos.toByteArray());
	}

	public static String encoderUnicode(String dataString) {
		char[] utfBytes = dataString.toCharArray();
		String unicodeBytes = "";
		for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {
			String hexB = Integer.toHexString(utfBytes[byteIndex]);
			if (hexB.length() <= 2) {
				hexB = "00" + hexB;
			}
			unicodeBytes = unicodeBytes + hexB;
		}
		return unicodeBytes;
	}

	// public static String decodeUnicode( final String dataStr ) {
	// int start = 0;
	// int end = 0;
	// final StringBuffer buffer = new StringBuffer();
	// while( start > -1 ) {
	// end = dataStr.indexOf( "\\\\u", start + 2 );
	// String charStr = "";
	// if( end == -1 ) {
	// charStr = dataStr.substring( start + 2, dataStr.length() );
	// } else {
	// charStr = dataStr.substring( start + 2, end);
	// }
	// char letter = (char) Integer.parseInt( charStr, 16 ); // 16进制parse整形字符串。
	// buffer.append( new Character( letter ).toString() );
	// start = end;
	// }
	// return buffer.toString();
	// }

	public static String numberToChinese(String numberStr) {
		StringBuilder resultStr = new StringBuilder();
		HashMap<String, String> numberChineseMap = new HashMap<String, String>();
		numberChineseMap.put("0", "零");
		numberChineseMap.put("1", "一");
		numberChineseMap.put("2", "二");
		numberChineseMap.put("3", "三");
		numberChineseMap.put("4", "四");
		numberChineseMap.put("5", "五");
		numberChineseMap.put("6", "六");
		numberChineseMap.put("7", "七");
		numberChineseMap.put("8", "八");
		numberChineseMap.put("9", "九");
		char[] numberCharArray = numberStr.toCharArray();
		for (char numberChar : numberCharArray) {
			String numberOneStr = String.valueOf(numberChar);
			if (numberChineseMap.get(numberOneStr) != null) {
				numberOneStr = numberChineseMap.get(numberOneStr);
			}
			resultStr.append(numberOneStr);
		}
		return resultStr.toString();
	}

	public static String obj2Str(Object obj) {
		StringBuilder sb = new StringBuilder();
		try {
			Field[] fields = obj.getClass().getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
				Field f = fields[i];
				String fieldName = f.getName();
				if ("serialVersionUID".equalsIgnoreCase(fieldName))
					continue;
				String stringLetter = fieldName.substring(0, 1).toUpperCase();
				String getName = "get" + stringLetter + fieldName.substring(1);
				Class<?> classType = obj.getClass();
				// 获取相应的方法
				Method getMethod = classType.getMethod(getName, new Class[] {});
				// 调用源对象的getXXX（）方法
				Object value = getMethod.invoke(obj, new Object[] {});
				sb.append(fieldName).append(':').append(value).append('\n');
			}
		} catch (NoSuchMethodException e) {
			sb.append(e.getMessage());
		} catch (IllegalArgumentException e) {
			sb.append(e.getMessage());
		} catch (IllegalAccessException e) {
			sb.append(e.getMessage());
		} catch (InvocationTargetException e) {
			sb.append(e.getMessage());
		}
		return sb.toString();
	}

	/**
	 * Md5+base64加密，用于用户密码
	 * 
	 * @param s
	 * @return
	 */
	public static String MD5BASE64(String s) {
		MessageDigest mdTemp;
		try {
			mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(s.getBytes());
			return new BASE64Encoder().encode(mdTemp.digest());
		} catch (NoSuchAlgorithmException e) {
			System.out.println("密码加密失败!" + e.getMessage());
			// return "4QrcOUm6Wau+VuBX8g+IPg==";
			return "";
		}
	}

	/**
	 * 是否是正整数
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isPositiveInteger(String str) {
		if (str == null)
			return false;
		Pattern pattern = Pattern.compile("^\\+?[1-9][0-9]*$");
		Matcher mc = pattern.matcher(str);
		return mc.matches();
	}

	/**
	 * 判断参数map中数字参数的有效性
	 * 
	 * @param params
	 * @param paramName
	 * @param defaultVal
	 */
	public static void checkNumPara(Map<String, String> params, String paramName, String defaultVal) {
		try {
			Integer.parseInt(params.get(paramName));
		} catch (Exception e) {
			params.put(paramName, defaultVal);
		}
	}

	/** The package separator character '.' */
	private static final char PACKAGE_SEPARATOR = '.';

	/** The inner class separator character '$'. */
	private static final char INNER_CLASS_SEPARATOR = '$';

	/** The CGLIB class separator character "$$". */
	private static final String CGLIB_CLASS_SEPARATOR = "$$";

	/** 换行符. */
	public static final String NEW_LINE = System.getProperty("line.separator", "\n");

	/** 文件分隔符. */
	public static final String FILE_SEPARATOR = System.getProperty("file.separator", "\\");

	/** The Constant EMPTY. */
	public static final String EMPTY = "";

	/** The Constant PAD_LIMIT. */
	public static final int PAD_LIMIT = 8192;

	/** The Constant DIGITS. */
	public static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

	public static void main(String[] args) {
		String s = " ";
		System.out.println(isEmpty(s));
	}

	/**
	 * 判断Collection是否为空.
	 * 
	 * @param collection
	 *            集合对象
	 * 
	 * @return 集合为空返回真
	 */
	public static boolean isEmpty(final Collection collection) {
		return (collection == null || collection.isEmpty());
	}

	/**
	 * 判断Map是否为空.
	 * 
	 * @param map
	 *            Map对象
	 * 
	 * @return map为空返回真
	 */
	public static boolean isEmpty(final Map map) {
		return (map == null || map.isEmpty());
	}

	/**
	 * 判断数组是否为空.
	 * 
	 * @param obj
	 *            数组
	 * 
	 * @return 数组为空返回真
	 */
	public static boolean isEmpty(final Object[] obj) {
		return (obj == null || obj.length == 0);
	}

	/**
	 * 判断字符串是否为空.
	 * 
	 * @param str
	 *            字符串
	 * 
	 * @return 字符串为空返回真
	 */
	public static boolean isEmpty(final String str) {
		return (str == null || !hasText(str.toString()));
	}

	/**
	 * 判断对象是否为空字符串.
	 * 
	 * @param obj
	 *            对象
	 * 
	 * @return 对象为空字符串返回真
	 */
	public static boolean isEmptyString(final Object obj) {
		return (obj == null || !hasText(obj.toString()));
	}

	/**
	 * 获取字符串.
	 * 
	 * @param map
	 *            Map对象
	 * @param key
	 *            键(不存在返回空字符串)
	 * 
	 * @return 字符串值
	 */
	public static String getString(final Map map, final Object key) {
		return getString(map, key, "");
	}

	/**
	 * 获取字符串.
	 * 
	 * @param map
	 *            Map对象
	 * @param key
	 *            键(不存在返回缺省值)
	 * @param defaultVal
	 *            缺省值
	 * 
	 * @return 字符串值
	 */
	public static String getString(final Map map, final Object key, final String defaultVal) {
		if (isEmpty(map) || key == null) {
			return defaultVal;
		}

		Object val = map.get(key);
		return val == null ? defaultVal : val.toString();
	}

	/**
	 * 集合转换为对象数组.
	 * 
	 * @param collection
	 *            集合
	 * 
	 * @return 字符串数组
	 * 
	 * @throws BaseException
	 *             the exception
	 */
	public static Object[] toArray(final Collection collection) throws BaseException {
		try {
			if (collection == null) {
				return null;
			}

			return collection.toArray();
		} catch (Exception ex) {
			throw new BaseException("集合转换对象数组出错", ex);
		}
	}

	/**
	 * 集合转换为字符串数组.
	 * 
	 * @param collection
	 *            集合
	 * 
	 * @return 字符串数组
	 * 
	 * @throws BaseException
	 *             the exception
	 */
	public static String[] toStringArray(final Collection collection) throws BaseException {
		try {
			if (collection == null) {
				return null;
			}
			return (String[]) collection.toArray(new String[collection.size()]);
		} catch (Exception ex) {
			throw new BaseException("集合转换字符串数组出错", ex);
		}
	}

	/**
	 * 枚举转换为字符串数组.
	 * 
	 * @param enumeration
	 *            枚举
	 * 
	 * @return 字符串数组
	 * 
	 * @throws BaseException
	 *             the exception
	 */
	public static String[] toStringArray(final Enumeration enumeration) throws BaseException {
		try {
			if (enumeration == null) {
				return null;
			}
			List list = Collections.list(enumeration);
			return (String[]) list.toArray(new String[list.size()]);
		} catch (Exception ex) {
			throw new BaseException("枚举转换字符串数组出错", ex);
		}
	}

	/**
	 * 集合转换为二维对象数组.
	 * 
	 * @param list
	 *            集合
	 * 
	 * @return 二维对象数组
	 * 
	 * @throws BaseException
	 *             the exception
	 */
	public static Object[][] toArrayOfArray(final List list) throws BaseException {
		try {
			if (list == null) {
				return null;
			}

			int size = list.size();
			Object[][] arr = new Object[size][];
			for (int i = 0; i < size; i++) {
				arr[i] = toArray((List) list.get(i));
			}

			return arr;
		} catch (Exception ex) {
			throw new BaseException("集合转换二维对象数组出错", ex);
		}
	}

	/**
	 * 转换数组为字符串.
	 * 
	 * @param arr
	 *            数组
	 * @param delim
	 *            分隔符（比如,）
	 * @param prefix
	 *            前缀(')
	 * @param suffix
	 *            后缀(')
	 * 
	 * @return 转换后的字符串
	 */
	public static String toDelimitedString(final Object[] arr, final String delim, final String prefix, final String suffix) {
		if (isEmpty(arr)) {
			return "";
		}

		StringBuffer sb = new StringBuffer();
		int len = arr.length;
		for (int i = 0; i < len; i++) {
			if (i > 0) {
				sb.append(delim);
			}
			sb.append(prefix).append(arr[i]).append(suffix);
		}
		return sb.toString();
	}

	/**
	 * 转换数组为字符串.
	 * 
	 * @param arr
	 *            数组
	 * @param delim
	 *            分隔符
	 * 
	 * @return 转换后的字符串
	 */
	public static String toDelimitedString(final Object[] arr, final String delim) {
		return toDelimitedString(arr, delim, "", "");
	}

	/**
	 * 转换数组为逗号分隔字符串.
	 * 
	 * @param arr
	 *            the arr
	 * 
	 * @return 逗号分隔的字符串
	 */
	public static String toCommaDelimitedString(final Object[] arr) {
		return toDelimitedString(arr, ",");
	}

	/**
	 * 转换集合为字符串.
	 * 
	 * @param coll
	 *            集合
	 * @param delim
	 *            分隔符（比如,）
	 * @param prefix
	 *            前缀(')
	 * @param suffix
	 *            后缀(')
	 * 
	 * @return 转换后的字符串
	 */
	public static String toDelimitedString(final Collection coll, final String delim, final String prefix, final String suffix) {
		if (isEmpty(coll)) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		Iterator it = coll.iterator();
		while (it.hasNext()) {
			sb.append(prefix).append(it.next()).append(suffix);
			if (it.hasNext()) {
				sb.append(delim);
			}
		}
		return sb.toString();
	}

	/**
	 * 转换集合为字符串.
	 * 
	 * @param coll
	 *            集合
	 * @param delim
	 *            分隔符
	 * 
	 * @return 转换后的字符串
	 */
	public static String toDelimitedString(final Collection coll, final String delim) {
		return toDelimitedString(coll, delim, "", "");
	}

	/**
	 * 转换集合为逗号分隔的字符串.
	 * 
	 * @param coll
	 *            the coll
	 * 
	 * @return 逗号分隔的字符串
	 */
	public static String toCommaDelimitedString(final Collection coll) {
		return toDelimitedString(coll, ",");
	}

	/**
	 * 转换对象为数组对象.
	 * 
	 * @param source
	 *            源对象
	 * 
	 * @return 对象数组
	 */
	public static Object[] toObjectArray(final Object source) {
		if (source instanceof Object[]) {
			return (Object[]) source;
		}
		if (source == null) {
			return new Object[0];
		}
		if (!source.getClass().isArray()) {
			throw new IllegalArgumentException("Source is not an array: " + source);
		}
		int length = Array.getLength(source);
		if (length == 0) {
			return new Object[0];
		}
		Class wrapperType = Array.get(source, 0).getClass();
		Object[] newArray = (Object[]) Array.newInstance(wrapperType, length);
		for (int i = 0; i < length; i++) {
			newArray[i] = Array.get(source, i);
		}
		return newArray;
	}

	/**
	 * 转换对象为集合.
	 * 
	 * @param source
	 *            源对象
	 * 
	 * @return 集合
	 */
	public static List arrayToList(final Object source) {
		return Arrays.asList(toObjectArray(source));
	}

	/**
	 * 获取类的名称.
	 * 
	 * @param className
	 *            类的全称
	 * 
	 * @return 类的名称
	 */
	public static String getShortClassName(final String className) {
		if (isEmpty(className))
			return "";

		int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR);
		int nameEndIndex = className.indexOf(CGLIB_CLASS_SEPARATOR);
		if (nameEndIndex == -1) {
			nameEndIndex = className.length();
		}
		String shortName = className.substring(lastDotIndex + 1, nameEndIndex);
		shortName = shortName.replace(INNER_CLASS_SEPARATOR, PACKAGE_SEPARATOR);
		return shortName;
	}

	/**
	 * 获取类的名称.
	 * 
	 * @param clazz
	 *            类对象
	 * 
	 * @return 类的名称
	 */
	public static String getShortClassName(final Class clazz) {
		return getShortClassName(clazz.getName());
	}

	/**
	 * 转换字节数组到基于HEX的字符数组.
	 * 
	 * @param data
	 *            字节数组
	 * 
	 * @return 基于HEX的字符数组
	 */
	public static char[] encodeHex(final byte[] data) {
		int l = data.length;
		char[] out = new char[l << 1];

		// two characters form the hex value.
		for (int i = 0, j = 0; i < l; i++) {
			out[j++] = DIGITS[(0xF0 & data[i]) >>> 4];
			out[j++] = DIGITS[0x0F & data[i]];
		}

		return out;
	}

	/**
	 * 转换字节数组到基于HEX的字符串.
	 * 
	 * @param data
	 *            字节数组
	 * 
	 * @return the char[]
	 */
	public static String toHexString(final byte[] data) {
		return new String(encodeHex(data));
	}

	/**
	 * 判断字符串长度.
	 * 
	 * @param str
	 *            字符串
	 * 
	 * @return 真表示非空，假表示空字符串
	 */
	public static boolean hasLength(final CharSequence str) {
		return (str != null && str.length() > 0);
	}

	/**
	 * 判断字符串长度.
	 * 
	 * @param str
	 *            字符串
	 * 
	 * @return 真表示非空，假表示空字符串
	 */
	public static boolean hasLength(final String str) {
		return hasLength((CharSequence) str);
	}

	/**
	 * 判断字符串是否有值.
	 * 
	 * @param str
	 *            字符串
	 * 
	 * @return 有值返回真，否则返回假
	 */
	public static boolean hasText(final CharSequence str) {
		if (!hasLength(str)) {
			return false;
		}
		int strLen = str.length();
		for (int i = 0; i < strLen; i++) {
			if (!Character.isWhitespace(str.charAt(i))) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 判断字符串是否有值.
	 * 
	 * @param str
	 *            字符串
	 * 
	 * @return 有值返回真，否则返回假
	 */
	public static boolean hasText(final String str) {
		return hasText((CharSequence) str);
	}

	/**
	 * 删除字符集空白元素.
	 * 
	 * @param str
	 *            字符串
	 * @return 处理后的字符串
	 */
	public static String trimWhitespace(final String str) {
		if (!hasLength(str)) {
			return str;
		}
		StringBuffer buf = new StringBuffer(str);
		while (buf.length() > 0 && Character.isWhitespace(buf.charAt(0))) {
			buf.deleteCharAt(0);
		}
		while (buf.length() > 0 && Character.isWhitespace(buf.charAt(buf.length() - 1))) {
			buf.deleteCharAt(buf.length() - 1);
		}
		return buf.toString();
	}

	/**
	 * 删除字符串中所有空白元素.
	 * 
	 * @param str
	 *            字符串
	 * 
	 * @return 处理后的字符串
	 */
	public static String trimAllWhitespace(final String str) {
		if (!hasLength(str)) {
			return str;
		}
		StringBuffer buf = new StringBuffer(str);
		int index = 0;
		while (buf.length() > index) {
			if (Character.isWhitespace(buf.charAt(index))) {
				buf.deleteCharAt(index);
			} else {
				index++;
			}
		}
		return buf.toString();
	}

	/**
	 * 删除字符串数组中元素的空白字符.
	 * 
	 * @param array
	 *            字符串数组
	 * 
	 * @return 处理后的字符串数组
	 */
	public static String[] trimArrayElements(final String[] array) {
		if (isEmpty(array)) {
			return new String[0];
		}
		String[] result = new String[array.length];
		for (int i = 0; i < array.length; i++) {
			String element = array[i];
			result[i] = (element != null ? element.trim() : null);
		}
		return result;
	}

	/**
	 * 删除字符串数组中重复的元素.
	 * 
	 * @param array
	 *            the array
	 * 
	 * @return 元素唯一的字符串数组
	 * 
	 * @throws BaseException
	 *             the exception
	 */
	public static String[] removeDuplicateStrings(final String[] array) throws BaseException {
		if (isEmpty(array)) {
			return array;
		}
		Set set = new TreeSet();
		for (int i = 0; i < array.length; i++) {
			set.add(array[i]);
		}
		return toStringArray(set);
	}

	/**
	 * 根据分隔符分隔字符串(忽略空白和忽略空元素）.
	 * 
	 * @param str
	 *            字符串
	 * @param delimiters
	 *            分隔符
	 * 
	 * @return 分隔后的字符串数组
	 * 
	 * @throws BaseException
	 *             the exception
	 */
	public static List tokenizeToList(final String str, final String delimiters) throws BaseException {
		return tokenizeToList(str, delimiters, true, true);
	}

	/**
	 * 根据分隔符分隔字符串.
	 * 
	 * @param str
	 *            字符串
	 * @param delimiters
	 *            分隔符
	 * @param trimTokens
	 *            是否忽略空白
	 * @param ignoreEmptyTokens
	 *            是否忽略空元素
	 * 
	 * @return 分隔后的字符串数组
	 * 
	 * @throws BaseException
	 *             the exception
	 */

	public static List tokenizeToList(final String str, final String delimiters, final boolean trimTokens, final boolean ignoreEmptyTokens) throws BaseException {

		if (str == null) {
			return new ArrayList();
		}
		StringTokenizer st = new StringTokenizer(str, delimiters);
		List tokens = new ArrayList();
		while (st.hasMoreTokens()) {
			String token = st.nextToken();
			if (trimTokens) {
				token = token.trim();
			}
			if (!ignoreEmptyTokens || token.length() > 0) {
				tokens.add(token);
			}
		}
		return tokens;
	}

	/**
	 * 测试此字符串是否以指定的前缀开始(忽略大小写）.
	 * 
	 * @param str
	 *            字符串
	 * @param prefix
	 *            前缀
	 * 
	 * @return 如果该参数表示的字符序列是此字符串表示的字符序列的前缀，则为 true；否则为 false。
	 */
	public static boolean startsWithIgnoreCase(final String str, final String prefix) {
		if (str == null || prefix == null) {
			return false;
		}
		if (str.startsWith(prefix)) {
			return true;
		}
		if (str.length() < prefix.length()) {
			return false;
		}
		String lcStr = str.substring(0, prefix.length()).toLowerCase();
		String lcPrefix = prefix.toLowerCase();
		return lcStr.equals(lcPrefix);
	}

	/**
	 * 测试此字符串是否以指定的后缀结束(忽略大小写）.
	 * 
	 * @param str
	 *            字符串
	 * @param suffix
	 *            后缀
	 * 
	 * @return 如果该参数表示的字符序列是此对象表示的字符序列的后缀，则返回 true；否则返回 false。
	 */
	public static boolean endsWithIgnoreCase(final String str, final String suffix) {
		if (str == null || suffix == null) {
			return false;
		}
		if (str.endsWith(suffix)) {
			return true;
		}
		if (str.length() < suffix.length()) {
			return false;
		}

		String lcStr = str.substring(str.length() - suffix.length()).toLowerCase();
		String lcSuffix = suffix.toLowerCase();
		return lcStr.equals(lcSuffix);
	}

	/**
	 * 检查文件或目录是否存在.
	 * 
	 * @param fileName
	 *            文件名
	 * 
	 * @return 为真存在，为否不存在
	 * 
	 * @throws BaseException
	 *             the exception
	 */
	public static boolean fileExists(final String fileName) throws BaseException {
		try {
			File file = new File(fileName);
			return file.exists();
		} catch (Exception ex) {
			throw new BaseException("检查文件" + fileName + "存在出错", ex);
		}
	}

	/**
	 * 删除文件或目录.
	 * 
	 * @param fileName
	 *            文件名
	 * 
	 * @return 是否删除成功
	 * 
	 * @throws BaseException
	 *             the exception
	 */
	public static boolean deleteFile(final String fileName) throws BaseException {
		try {
			File file = new File(fileName);
			return file.delete();
		} catch (Exception ex) {
			throw new BaseException("删除文件" + fileName + "出错", ex);
		}
	}

	/**
	 * 读取文件.
	 * 
	 * @param fileName
	 *            文件名
	 * @return 文件内容
	 * @throws BaseException
	 *             the exception
	 */
	public static byte[] readFile(final String fileName) throws BaseException {
		BufferedInputStream bis = null;
		try {
			File file = new File(fileName);

			long len = file.length();
			byte[] bytes = new byte[(int) len];

			bis = new BufferedInputStream(new FileInputStream(file));
			bis.read(bytes);

			return bytes;

		} catch (Exception ex) {
			throw new BaseException("读取文件" + fileName + "出错", ex);
		} finally {
			try {
				if (bis != null) {
					bis.close();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	/**
	 * 使用空分隔符连接数组.
	 * 
	 * @param array
	 *            数组
	 * 
	 * @return 字符串
	 */
	public static String join(final Object[] array) {
		return join(array, null);
	}

	/**
	 * 使用指定分隔符连接数组.
	 * 
	 * @param array
	 *            数组
	 * @param separator
	 *            分隔符
	 * 
	 * @return 字符串
	 */
	public static String join(final Object[] array, final String separator) {
		if (array == null) {
			return null;
		}
		return join(array, separator, 0, array.length);
	}

	/**
	 * 使用指定分隔符连接数组.
	 * 
	 * @param array
	 *            数组
	 * @param separator
	 *            分隔符
	 * @param startIndex
	 *            开始索引号
	 * @param endIndex
	 *            结束索引号
	 * 
	 * @return 字符串
	 */
	public static String join(final Object[] array, String separator, final int startIndex, final int endIndex) {
		if (array == null) {
			return null;
		}
		if (separator == null) {
			separator = EMPTY;
		}

		// endIndex - startIndex > 0: Len = NofStrings *(len(firstString) +
		// len(separator))
		// (Assuming that all Strings are roughly equally long)
		int bufSize = (endIndex - startIndex);
		if (bufSize <= 0) {
			return EMPTY;
		}

		bufSize *= ((array[startIndex] == null ? 16 : array[startIndex].toString().length()) + separator.length());

		StringBuffer buf = new StringBuffer(bufSize);

		for (int i = startIndex; i < endIndex; i++) {
			if (i > startIndex) {
				buf.append(separator);
			}
			if (array[i] != null) {
				buf.append(array[i]);
			}
		}
		return buf.toString();
	}

	/**
	 * 使用指定分隔符连接迭代对象.
	 * 
	 * @param iterator
	 *            the iterator
	 * @param separator
	 *            分隔符
	 * @return 字符串
	 */
	public static String join(final Iterator iterator, final String separator) {

		// handle null, zero and one elements before building a buffer
		if (iterator == null) {
			return null;
		}
		if (!iterator.hasNext()) {
			return EMPTY;
		}
		Object first = iterator.next();
		if (!iterator.hasNext()) {
			return first == null ? EMPTY : first.toString();
		}

		// two or more elements
		StringBuffer buf = new StringBuffer(256); // Java default is 16,
		// probably too small
		if (first != null) {
			buf.append(first);
		}

		while (iterator.hasNext()) {
			if (separator != null) {
				buf.append(separator);
			}
			Object obj = iterator.next();
			if (obj != null) {
				buf.append(obj);
			}
		}
		return buf.toString();
	}

	/**
	 * 使用指定分隔符连接集合.
	 * 
	 * @param collection
	 *            集合对象
	 * @param separator
	 *            分隔符
	 * 
	 * @return 字符串
	 */
	public static String join(final Collection collection, final String separator) {
		if (collection == null) {
			return null;
		}
		return join(collection.iterator(), separator);
	}

	/**
	 * 使用指定分隔符连接列表.
	 * 
	 * @param lst
	 *            列表
	 * @param colName
	 *            列名
	 * @param spearator
	 *            分隔符
	 * @return the string
	 */
	public static String joinList(final List lst, final String colName, final String spearator) {
		if (lst == null) {
			return null;
		}

		Set set = new LinkedHashSet();
		String str = null;
		for (int i = 0; i < lst.size(); i++) {
			str = getString((Map) lst.get(i), colName);
			if (str != null && str.length() > 0) {
				set.add(str);
			}
		}

		return join(set, spearator);
	}

	/**
	 * 使用指定分隔符连接列表.
	 * 
	 * @param lst
	 *            列表
	 * @param colName
	 *            列名
	 * @param spearator
	 *            分隔符
	 * @return the string
	 */
	public static String joinArray(final String[][] strArray, final int index, final String spearator) {
		if (strArray == null) {
			return null;
		}

		Set set = new LinkedHashSet();
		String str = null;
		for (int i = 0; i < strArray.length; i++) {
			str = strArray[i][index];
			if (str != null && str.length() > 0) {
				set.add(str);
			}
		}

		return join(set, spearator);
	}

	/**
	 * Performs the logic for the <code>split</code> and
	 * <code>splitPreserveAllTokens</code> methods that return a maximum array
	 * length.
	 * 
	 * @param str
	 *            the String to parse, may be <code>null</code>
	 * @param separatorChars
	 *            the separate character
	 * @param max
	 *            the maximum number of elements to include in the array. A zero
	 *            or negative value implies no limit.
	 * @param preserveAllTokens
	 *            if <code>true</code>, adjacent separators are treated as empty
	 *            token separators; if <code>false</code>, adjacent separators
	 *            are treated as one separator.
	 * @return an array of parsed Strings, if null String input
	 */
	private static String[] splitWorker(final String str, final String separatorChars, final int max, final boolean preserveAllTokens) {
		// Performance tuned for 2.0 (JDK1.4)
		// Direct code is quicker than StringTokenizer.
		// Also, StringTokenizer uses isSpace() not isWhitespace()

		if (str == null) {
			return null;
		}
		int len = str.length();
		if (len == 0) {
			return new String[0];
		}
		List list = new ArrayList();
		int sizePlus1 = 1;
		int i = 0, start = 0;
		boolean match = false;
		boolean lastMatch = false;
		if (separatorChars == null) {
			// Null separator means use whitespace
			while (i < len) {
				if (Character.isWhitespace(str.charAt(i))) {
					if (match || preserveAllTokens) {
						lastMatch = true;
						if (sizePlus1++ == max) {
							i = len;
							lastMatch = false;
						}
						list.add(str.substring(start, i));
						match = false;
					}
					start = ++i;
					continue;
				}
				lastMatch = false;
				match = true;
				i++;
			}
		} else if (separatorChars.length() == 1) {
			// Optimise 1 character case
			char sep = separatorChars.charAt(0);
			while (i < len) {
				if (str.charAt(i) == sep) {
					if (match || preserveAllTokens) {
						lastMatch = true;
						if (sizePlus1++ == max) {
							i = len;
							lastMatch = false;
						}
						list.add(str.substring(start, i));
						match = false;
					}
					start = ++i;
					continue;
				}
				lastMatch = false;
				match = true;
				i++;
			}
		} else {
			// standard case
			while (i < len) {
				if (separatorChars.indexOf(str.charAt(i)) >= 0) {
					if (match || preserveAllTokens) {
						lastMatch = true;
						if (sizePlus1++ == max) {
							i = len;
							lastMatch = false;
						}
						list.add(str.substring(start, i));
						match = false;
					}
					start = ++i;
					continue;
				}
				lastMatch = false;
				match = true;
				i++;
			}
		}
		if (match || (preserveAllTokens && lastMatch)) {
			list.add(str.substring(start, i));
		}
		return (String[]) list.toArray(new String[list.size()]);
	}

	/**
	 * 使用空格分隔字符串.
	 * 
	 * @param str
	 *            字符串
	 * 
	 * @return 字符串数组
	 */
	public static String[] split(final String str) {
		return split(str, null, -1);
	}

	/**
	 * 使用指定分隔符分隔字符串.
	 * 
	 * @param str
	 *            字符串
	 * @param separatorChars
	 *            分隔符
	 * 
	 * @return 字符串数组
	 */
	public static String[] split(final String str, final String separatorChars) {
		return splitWorker(str, separatorChars, -1, false);
	}

	/**
	 * 使用指定分隔符分隔字符串.
	 * 
	 * @param str
	 *            字符串
	 * @param separatorChars
	 *            分隔符
	 * @param max
	 *            最大个数
	 * 
	 * @return 字符串数组
	 */
	public static String[] split(final String str, final String separatorChars, final int max) {
		return splitWorker(str, separatorChars, max, false);
	}

	/**
	 * 获取左边指定个数的字符串.
	 * 
	 * @param str
	 *            字符串
	 * @param len
	 *            长度
	 * 
	 * @return 子字符串
	 */
	public static String left(final String str, final int len) {
		if (str == null) {
			return null;
		}
		if (len < 0) {
			return EMPTY;
		}
		if (str.length() <= len) {
			return str;
		}
		return str.substring(0, len);
	}

	/**
	 * 获取中间指定个数的字符串.
	 * 
	 * @param str
	 *            字符串
	 * @param pos
	 *            位置
	 * @param len
	 *            长度
	 * 
	 * @return 子字符串
	 */
	public static String mid(final String str, int pos, final int len) {
		if (str == null) {
			return null;
		}
		if (len < 0 || pos > str.length()) {
			return EMPTY;
		}
		if (pos < 0) {
			pos = 0;
		}
		if (str.length() <= (pos + len)) {
			return str.substring(pos);
		}
		return str.substring(pos, pos + len);
	}

	/**
	 * 获取右边指定个数的字符串.
	 * 
	 * @param str
	 *            字符串
	 * @param len
	 *            长度
	 * 
	 * @return 子字符串
	 */
	public static String right(final String str, final int len) {
		if (str == null) {
			return null;
		}
		if (len < 0) {
			return EMPTY;
		}
		if (str.length() <= len) {
			return str;
		}
		return str.substring(str.length() - len);
	}

	/**
	 * Padding.
	 * 
	 * @param repeat
	 *            the repeat
	 * @param padChar
	 *            the pad char
	 * @return the string
	 */
	private static String padding(final int repeat, final char padChar) {
		if (repeat < 0) {
			return null;
		}
		final char[] buf = new char[repeat];
		for (int i = 0; i < buf.length; i++) {
			buf[i] = padChar;
		}
		return new String(buf);
	}

	/**
	 * 左填充字符串.
	 * 
	 * @param str
	 *            字符串
	 * @param size
	 *            填充后的字符串长度
	 * @param padChar
	 *            填充字符
	 * 
	 * @return 字符串
	 */
	public static String leftPad(final String str, final int size, final char padChar) {
		if (str == null) {
			return null;
		}
		int pads = size - str.length();
		if (pads <= 0) {
			return str; // returns original String when possible
		}
		if (pads > PAD_LIMIT) {
			return leftPad(str, size, String.valueOf(padChar));
		}
		return padding(pads, padChar).concat(str);
	}

	/**
	 * 左填充字符串.
	 * 
	 * @param str
	 *            字符串
	 * @param size
	 *            填充后的字符串长度
	 * @param padStr
	 *            填充字符串
	 * 
	 * @return 字符串
	 */
	public static String leftPad(final String str, final int size, String padStr) {
		if (str == null) {
			return null;
		}
		if (isEmpty(padStr)) {
			padStr = " ";
		}
		int padLen = padStr.length();
		int strLen = str.length();
		int pads = size - strLen;
		if (pads <= 0) {
			return str; // returns original String when possible
		}
		if (padLen == 1 && pads <= PAD_LIMIT) {
			return leftPad(str, size, padStr.charAt(0));
		}

		if (pads == padLen) {
			return padStr.concat(str);
		} else if (pads < padLen) {
			return padStr.substring(0, pads).concat(str);
		} else {
			char[] padding = new char[pads];
			char[] padChars = padStr.toCharArray();
			for (int i = 0; i < pads; i++) {
				padding[i] = padChars[i % padLen];
			}
			return new String(padding).concat(str);
		}
	}

	/**
	 * 右填充字符串.
	 * 
	 * @param str
	 *            字符串
	 * @param size
	 *            填充后的字符串长度
	 * @param padChar
	 *            填充字符
	 * 
	 * @return 字符串
	 */
	public static String rightPad(final String str, final int size, final char padChar) {
		if (str == null) {
			return null;
		}
		int pads = size - str.length();
		if (pads <= 0) {
			return str; // returns original String when possible
		}
		if (pads > PAD_LIMIT) {
			return rightPad(str, size, String.valueOf(padChar));
		}
		return str.concat(padding(pads, padChar));
	}

	/**
	 * 右填充字符串.
	 * 
	 * @param str
	 *            字符串
	 * @param size
	 *            填充后的字符串长度
	 * @param padStr
	 *            填充字符串
	 * 
	 * @return 字符串
	 */
	public static String rightPad(final String str, final int size, String padStr) {
		if (str == null) {
			return null;
		}
		if (isEmpty(padStr)) {
			padStr = " ";
		}
		int padLen = padStr.length();
		int strLen = str.length();
		int pads = size - strLen;
		if (pads <= 0) {
			return str; // returns original String when possible
		}
		if (padLen == 1 && pads <= PAD_LIMIT) {
			return rightPad(str, size, padStr.charAt(0));
		}

		if (pads == padLen) {
			return str.concat(padStr);
		} else if (pads < padLen) {
			return str.concat(padStr.substring(0, pads));
		} else {
			char[] padding = new char[pads];
			char[] padChars = padStr.toCharArray();
			for (int i = 0; i < pads; i++) {
				padding[i] = padChars[i % padLen];
			}
			return str.concat(new String(padding));
		}
	}

	/**
	 * 替换字符串.
	 * 
	 * @param text
	 *            the text
	 * @param searchString
	 *            the search string
	 * @param replacement
	 *            the replacement
	 * 
	 * @return the string
	 */
	public static String replace(final String text, final String searchString, final String replacement) {
		return replace(text, searchString, replacement, -1);
	}

	/**
	 * 替换字符串.
	 * 
	 * @param text
	 *            the text
	 * @param searchString
	 *            the search string
	 * @param replacement
	 *            the replacement
	 * @param max
	 *            the max
	 * 
	 * @return the string
	 */
	public static String replace(final String text, final String searchString, final String replacement, int max) {
		if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) {
			return text;
		}
		int start = 0;
		int end = text.indexOf(searchString, start);
		if (end == -1) {
			return text;
		}
		int replLength = searchString.length();
		int increase = replacement.length() - replLength;
		increase = (increase < 0 ? 0 : increase);
		increase *= (max < 0 ? 16 : (max > 64 ? 64 : max));
		StringBuffer buf = new StringBuffer(text.length() + increase);
		while (end != -1) {
			buf.append(text.substring(start, end)).append(replacement);
			start = end + replLength;
			if (--max == 0) {
				break;
			}
			end = text.indexOf(searchString, start);
		}
		buf.append(text.substring(start));
		return buf.toString();
	}

	/**
	 * 数组转换字符串.
	 * 
	 * @param a
	 *            数组对象
	 * @param separator
	 *            分隔符
	 * @return the string
	 */
	public static String arrayToString(final Object[] a, final String separator) {
		StringBuffer result = new StringBuffer();
		String split = (separator == null ? "" : separator);
		if (a != null && a.length > 0) {
			result.append(a[0]);
			for (int i = 1; i < a.length; i++) {
				result.append(split);
				result.append(a[i]);
			}
		}

		return result.toString();
	}

	/**
	 * 删除sql参数无效字符.
	 * 
	 * @param obj
	 *            the obj
	 * @return the string
	 */
	public static String trimSqlParam(final Object obj) {
		if (obj == null) {
			return null;
		}

		String str = obj.toString().trim();
		if (!hasLength(str)) {
			return str;
		}

		str = escapeSqlParam(str);
		return replace(str, "%", "");
	}

	/**
	 * 编码sql参数(不处理%符号).
	 * 
	 * @param str
	 *            the str
	 * @return the string
	 */
	public static String escapeSqlParam(final String str) {
		if (str == null) {
			return null;
		}

		return replace(str, "'", "''");
	}

	/**
	 * 字符串大写处理.
	 * 
	 * @param str
	 *            the str
	 * @return the string
	 */
	public static String toUpperCase(final String str) {
		return str == null ? null : str.toUpperCase();
	}

	/**
	 * 字符串小写处理.
	 * 
	 * @param str
	 *            the str
	 * @return the string
	 */
	public static String toLowerCase(final String str) {
		return str == null ? null : str.toLowerCase();
	}

	/**
	 * @功能 根据给定的regex正则表达式，验证给定的字符串input是否符合
	 * @param input
	 *            需要被验证的字符串
	 * @param regex
	 *            正则表达式
	 * @return boolean 型值
	 */
	public static boolean verifyWord(String input, String regex) {
		if (input == null) {
			input = "";
		}

		if (regex == null) {
			regex = "";
		}

		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(input);
		boolean flag = m.matches();

		return flag;
	}

	/**
	 * 获取UUID字符串.
	 * 
	 * @return the uUID
	 */
	public static String getUUID() {
		UUID uuid = UUID.randomUUID();
		String sud = uuid.toString();

		sud = sud.replaceAll("-", "");
		return sud;
	}

	/**
	 * 构建模式列表（逗号分隔).
	 * 
	 * @param patterns
	 *            the patterns
	 * @return the list
	 */
	public static List<Pattern> buildPatternsList(final String patterns) {
		if (null != patterns && patterns.trim().length() != 0) {
			List<Pattern> list = new ArrayList<Pattern>();
			String[] tokens = patterns.split(",");

			for (String token : tokens) {
				try {
					list.add(Pattern.compile(token.trim()));
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
			return list;
		} else {
			return null;
		}
	}

	/**
	 * 获取有效列
	 * 
	 * @param COLS
	 * @param map
	 * @return
	 */
	public static Set<String> getValidCols(String[] COLS, Map<String, String> map) {
		Set<String> cols = new HashSet<String>();
		for (String col : COLS) {
			if (map.containsKey(col)) {
				cols.add(col);
			}
		}

		return cols;
	}

}
